package com.example.booksdeal.basic;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.booksdeal.BmobDBO.User;
import com.example.booksdeal.R;
import com.example.booksdeal.util.DBOpenHelper;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

public class RegisterActivity extends AppCompatActivity {

    private long exitTime = 0;
    private DBOpenHelper dbOpenHelper;  //声明DBOpenHelper对象
    private EditText mName,mPwd,mRepwd,mNickname,mTel;
    private TextView mNameTv,mPwdTv,mRepwdTv,mNicknameTv,mTelTv;
    private Button mSignup;
    private String usernm,pwd,repwd,nicknm,tel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (Build.VERSION.SDK_INT >= 21){
//            View decorView = getWindow().getDecorView();
//            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            getWindow().setStatusBarColor(Color.TRANSPARENT);
//        }

        setContentView(R.layout.activity_register);
        dbOpenHelper = new DBOpenHelper(RegisterActivity.this,"db_booksdeal.db",null,1);  //实例化DBOpenHelper对象，用来创建数据库
        mName = findViewById(R.id.name);
        mPwd = findViewById(R.id.pwd);
        mRepwd = findViewById(R.id.repwd);
        mNickname = findViewById(R.id.nickname);
        mTel = findViewById(R.id.tel);
        mNameTv = findViewById(R.id.name_tx);
        mPwdTv = findViewById(R.id.pwd_tx);
        mRepwdTv = findViewById(R.id.repwd_tx);
        mNicknameTv = findViewById(R.id.nickname_tx);
        mTelTv = findViewById(R.id.tel_tx);
        mSignup = findViewById(R.id.signup);

        usernm = mName.getText().toString();
        pwd = mPwd.getText().toString();
        repwd = mRepwd.getText().toString();
        nicknm = mNickname.getText().toString();
        tel = mTel.getText().toString();

        mName.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener(){

            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    // 此处为得到焦点时的处理内容
                    if(mName.getText().toString().trim().length()<6)
                        mNameTv.setVisibility(View.VISIBLE);
                    else   mNameTv.setVisibility(View.INVISIBLE);

                } else {
                    // 此处为失去焦点时的处理内容
                    if(mName.getText().toString().trim().length()<6)
                        mNameTv.setVisibility(View.VISIBLE);
                    else   mNameTv.setVisibility(View.INVISIBLE);
                }
            }
        });
        mPwd.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener(){

            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    // 此处为得到焦点时的处理内容
                    if(mPwd.getText().toString().trim().length()<6)
                        mPwdTv.setVisibility(View.VISIBLE);
                    else   mPwdTv.setVisibility(View.INVISIBLE);

                } else {
                    // 此处为失去焦点时的处理内容
                    if(mPwd.getText().toString().trim().length()<6)
                        mPwdTv.setVisibility(View.VISIBLE);
                    else   mPwdTv.setVisibility(View.INVISIBLE);
                }
            }
        });
        mRepwd.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener(){

            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    // 此处为得到焦点时的处理内容
                    if(mRepwd.getText().toString().equals(mPwd.getText().toString()))
                        mRepwdTv.setVisibility(View.INVISIBLE);

                    else   mRepwdTv.setVisibility(View.VISIBLE);


                } else {
                    // 此处为失去焦点时的处理内容
                    if(mRepwd.getText().toString().equals(mPwd.getText().toString()))
                        mRepwdTv.setVisibility(View.INVISIBLE);
                    else mRepwdTv.setVisibility(View.VISIBLE);
                }
            }
        });
        mNickname.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener(){

            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    // 此处为得到焦点时的处理内容
                    if(mNickname.getText().toString().trim().isEmpty()) mNicknameTv.setVisibility(View.VISIBLE);
                    else  mNicknameTv.setVisibility(View.INVISIBLE);

                } else {
                    // 此处为失去焦点时的处理内容
                    if(mNickname.getText().toString().trim().isEmpty()) mNicknameTv.setVisibility(View.VISIBLE);
                    else   mNicknameTv.setVisibility(View.INVISIBLE);
                }
            }
        });
        mTel.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener(){

            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    // 此处为得到焦点时的处理内容
                    if(mTel.getText().toString().trim().isEmpty()) mTelTv.setVisibility(View.VISIBLE);
                    else  mTelTv.setVisibility(View.INVISIBLE);

                } else {
                    // 此处为失去焦点时的处理内容
                    if(mTel.getText().toString().trim().isEmpty()) mTelTv.setVisibility(View.VISIBLE);
                    else   mTelTv.setVisibility(View.INVISIBLE);
                }
            }
        });
        mSignup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                usernm = mName.getText().toString();
                pwd = mPwd.getText().toString();
                repwd = mRepwd.getText().toString();
                nicknm = mNickname.getText().toString();
                tel = mTel.getText().toString();
                if(usernm.trim().length()<6 || pwd.trim().length()<6 || nicknm.trim().isEmpty() || tel.trim().isEmpty() || pwd.trim().equals(repwd)==false)
                    Toast.makeText(RegisterActivity.this,"信息不符合规范！",Toast.LENGTH_SHORT).show();
                else {
//                    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
//                    Cursor cursor = db.query("UserInfo", null, "username=?", new String[]{usernm}, null, null, null);
//                    if (cursor != null && cursor.getCount() >= 1) {
//                        Toast.makeText(RegisterActivity.this, "账号已存在", Toast.LENGTH_SHORT).show();
//                        cursor.close();
//                    } else {
                        regUser();
                 //   }
                }
            }
        });
    }

    /**
     * 注册用户（同步需注意）
     */
    private void regUser(){
        BmobQuery<User> categoryBmobQuery = new BmobQuery<>();
        categoryBmobQuery.addWhereEqualTo("username", usernm);
        categoryBmobQuery.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null) {

                    if (object.size()!=0){
                        // 点击按钮 代表登录成功
                        Toast.makeText(RegisterActivity.this, "注册失败，账号已存在"+object.size(), Toast.LENGTH_SHORT).show();
                    }else {
                        User user =new User();
                        user.setUsername(usernm);
                        user.setPassword(pwd);
                        user.setNickname(nicknm);
                        user.setTelephone(tel);
                        user.signUp(new SaveListener<BmobUser>() {
                            @Override
                            public void done(BmobUser user, BmobException e) {
                                if(e==null)
                                {
                                    Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                                    finish();
                                }else
                                {
                                    Log.e("注册失败", "原因: ",e );
                                }

                            }
                        });
                    }
                }
            }
        });
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    EMClient.getInstance().createAccount(mName.getText().toString().trim(), mPwd.getText().toString().trim());
//                    insertData(dbOpenHelper.getReadableDatabase(),usernm,pwd,nicknm,tel);  //添加用户
//                    Log.i("TAG", "register: 注册成功");
//                    Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
//                } catch (HyphenateException e) {
//                    //注册失败会抛出异常
//                    e.printStackTrace();
//                    Log.i("TAG", "register: 注册失败" + e.getErrorCode() + " , " + e.getMessage());
//                }
//            }
//        }).start();
    }

    //返回登陆界面
    public void backlogin(View view) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK); // 禁止返回
        intent.setClass(RegisterActivity.this,LoginActivity.class);
        startActivity(intent);
    }
    //插入数据的方法
    private void insertData (SQLiteDatabase sqLiteDatabase,String usernm,String pwd,String nicknm,String tel) {
        ContentValues values = new ContentValues();
        values.put("username",usernm);  //保存账号
        values.put("password",pwd);  //保存密码
        values.put("nickname",nicknm);  //保存昵称
        values.put("telephone",tel);  //保存电话号码
        sqLiteDatabase.insert("UserInfo",null,values); //执行插入操作
    }

    // 实现再按一次返回键退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper!=null){
            dbOpenHelper.close();  //关闭数据库连接
        }
    }
}
